<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-12 04:22:42
 * @Last Modified by:   Wang Chunsheng 2192138785@qq.com
 * @Last Modified time: 2020-03-30 14:03:31
 */

namespace common\addons\diandi_shop\services;

use common\addons\diandi_shop\models\DdDiandiShopCart;
use common\addons\diandi_shop\models\DdGoods;
use common\addons\diandi_shop\models\DdSpecValue;
use Yii;
use yii\web\NotFoundHttpException;
use yii\web\UnprocessableEntityHttpException;
use yii\helpers\Json;
use common\services\BaseService;
use common\helpers\ArrayHelper;
use common\helpers\ErrorsHelper;
use common\helpers\ImageHelper;
use common\helpers\ResultHelper;
use common\models\DdMenuCate;
use common\models\DdUser;
use common\models\DdUserAddress;

/**
 * Class SmsService
 * @package common\services\backend
 * @author chunchun <2192138785@qq.com>
 */
class CartService extends BaseService
{
    public static function confirm($user_id, $goods_id, $num, $spec_id = '')
    {
        $where = [
            'user_id' => $user_id, 'goods_id' => $goods_id
        ];

        if ($spec_id) {
            $where['spec_id'] = $spec_id;
        }

        $isHave =  DdDiandiShopCart::findOne($where);
        $spec_value_ids = explode('_', $spec_id);
        $specVal = DdSpecValue::find()
            ->where(['spec_value_id' => $spec_value_ids])
            ->indexBy('spec_value_id')
            ->all();
        $specs = [];
        if (!empty($spec_value_ids)) {
            foreach ($spec_value_ids as $key => $item) {
                $ks[] = $specVal[$item]['spec_value'];
            }
            $newKey = implode('_', $ks);
            $specs[$spec_id] = $newKey;
        }
        $goods = DdGoods::find()->where(['goods_id' => $goods_id])->one();

        // 校验库存
        if ($goods['stock'] < $num) {
            return ResultHelper::json(401, $goods['goods_name'] . '库存不足', []);
        }

        if (!empty($isHave)) {
            if ($num < 0) {
                return ResultHelper::json(401, '商品数量不能为负数', []);
            } elseif ($num == 0) {
                DdDiandiShopCart::deleteAll($where);
            }

            $total_price = $num * $goods['goods_price'];

            DdDiandiShopCart::updateAll(['number' => $num, 'total_price' => $total_price], $where);
        } else {
            $total_price = $num * $goods['goods_price'];

            $DdDiandiShopCart = new DdDiandiShopCart();
            $datas = [
                'user_id' => $user_id,
                'goods_id' => $goods_id,
                'number' => $num,
                'total_price' => $total_price,
                'spec_id' => $spec_id,
                'spec_val' => $specs[$spec_id],
                'create_time' => time()
            ];
            if (!$DdDiandiShopCart->load($datas, '') || !$DdDiandiShopCart->save()) {
                return ErrorsHelper::getModelError($DdDiandiShopCart);
            }
        }
        return self::list($user_id);
    }


    public static function list($user_id)
    {

        $list = DdDiandiShopCart::find()
            ->where(['user_id' => $user_id])
            ->with(['goods', 'goodsSpec'])
            ->asArray()
            ->indexBy('goods_id')
            ->all();

        $total_price = 0;

        if (!empty($list)) {
            foreach ($list as &$item) {
                // 商品总数
                $lists['goodsTotalNumber'] += $item['number'];
                // 总价格
                $total_price += $item['total_price'];

                // 处理图片
                $item['goods']['thumb'] = ImageHelper::tomedia($item['goods']['thumb']);
            }
            $lists['goods'] = $list;
            // 计算运费
            $lists['freight'] = self::freight();
            $lists['total_price'] = number_format($total_price + $lists['freight'], 2, '.', '');
        } else {
            $lists['goodsTotalNumber'] = 0;
            // 总价格
            $lists['total_price'] = 0;
            $lists['goods'] = [];
            // 计算运费
            $lists['freight'] = self::freight();
        }
        return $lists;
    }


    public static function clearAll($user_id)
    {
        $res =  DdDiandiShopCart::deleteAll(['user_id' => $user_id]);
        return self::list($user_id);
    }

    public static function freight()
    {
        return  Yii::$app->settings->get('DiandiShopStroe', 'shippingDees');
    }
}
